const app = getApp()
import { getDkDetail, setZan, checkInfo } from "../../utils/request"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    baseUrl: app.baseUrl,
    shareList: [
      { url: '/assets/share1.png', title: '微信好友' },
      // { url: '/assets/share2.png', title: '朋友圈' },
      { url: '/assets/share3.png', title: '保存到本地' },
    ],
    id: '',
    obj: {},
    alert: false,
    tempFilePath: null,
    shareId: null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      id: options.id || options.shareId,
      shareId: options.shareId || null
    }, () => {
      this.getDetail(this.data.id)
    })

  },
  async getDetail(id) {
    const data = await getDkDetail({ id })
    if (data.code !== '1') return
    data.data.image = data.data.image.split("|").map(item => `${this.data.baseUrl}${item}`)
    data.data.create_time = app.func.changeTime(data.data.create_time)
    data.data.share_image = this.data.baseUrl + data.data.share_image
    data.data.mini_image = this.data.baseUrl + data.data.mini_image

    this.setData({
      obj: data.data
    })
  },
  async jumpClock() {
    if (this.data.shareId) {
      wx.reLaunch({
        url: '/pages/main/index',
      });
    }else{
    const data = await checkInfo()
    if (data.code !== "1") return
    if (data.data) {
      wx.navigateTo({
        url: '/pages/clocking/index',
      })
    } else {
      app.func.Toast.none("请完善个人信息")
      setTimeout(() => {
        wx.navigateTo({
          url: '/pages/person_info/index?type=1',
        })
      }, 1000)
    }
  }

  },
  jumpImg(event) {
    app.preview(event, this.data.obj.image)
  },
  async jumpShare() {
    wx.showLoading({ title: '绘制中' })
    const { obj } = this.data
    const arr = [obj.mini_image, obj.user_image, obj.share_image]
    const data = await app.func.localityImg(arr)
    if (data) {
      this.getImgDetail(data)
    }

  },
  async jumpZan() {
    const { obj } = this.data
    const data = await setZan({ id: obj.id })
    if (data.code !== '1') return
    app.func.Toast.success("点赞成功")
    obj.like_count++
    this.setData({
      obj
    })
  },
  jumpClose() {
    this.setData({
      alert: false
    })
  },
  save() {
    app.func.downImg(this.data.tempFilePath)
  },
  getImgInfo(url) {
    wx.getImageInfo({
      src: url,
      success(res) {
        return res.height
      }
    })
  },

  circleImg: function (ctx, img, x, y, r) {  //圆形头像
    ctx.save();
    var d = 2 * r;
    var cx = x + r;
    var cy = y + r;
    ctx.beginPath();
    ctx.arc(cx, cy, r, 0, 2 * Math.PI);
    ctx.clip();
    ctx.drawImage(img, x, y, d, d);
  },
  //海报
  getImgDetail(res) {
    const {
      obj,
    } = this.data
    const query = wx.createSelectorQuery().in(this)
    query.selectAll('#getHeight').boundingClientRect()
    const that = this
    query.exec((rect) => {
      const ctx = wx.createCanvasContext('myCanvas')
      // 背景
      ctx.drawImage("/assets/canvasDraw.png", 0, 0, 375, 667)
      ctx.font = 'normal bold 18px sans-serif';
      ctx.setFillStyle('#fff')
      ctx.fillText(obj.place, 20, 120)

      ctx.font = 'normal normal 13px sans-serif';
      ctx.setFillStyle('#fff')
      ctx.fillText(obj.place_address, 20, 140)


      ctx.drawImage(res[0], 20, 160, 335, 240)


      this.circleImg(ctx, res[1], 40, 440, 20);
      ctx.restore();  //需要编辑canvas内容则需要写入


      ctx.font = 'normal bold 16px sans-serif';
      ctx.setFillStyle('#333')
      ctx.fillText(obj.name, 90, 470)


      ctx.font = 'normal normal 16px sans-serif';
      ctx.setFillStyle('#333')
      ctx.fillText(`我已参加 `, 40, 510)

      ctx.font = 'normal bold 16px sans-serif';
      ctx.setFillStyle('#E53B3B')
      ctx.fillText(`${obj.clock_count}`, 110, 510)

      ctx.font = 'normal normal 16px sans-serif';
      ctx.setFillStyle('#333')
      ctx.fillText(` 次打卡`, 130, 510)

      ctx.font = 'normal normal 16px sans-serif';
      ctx.setFillStyle('#333')
      ctx.fillText(`点赞：`, 40, 540)

      ctx.font = 'normal bold 16px sans-serif';
      ctx.setFillStyle('#E53B3B')
      ctx.fillText(`${obj.like_count}`, 90, 540)


      ctx.drawImage(res[2], 260, 440, 77, 77)

      ctx.font = 'normal normal 10px sans-serif';
      ctx.setFillStyle('#333')
      // ctx.setTextAlign('center');
      ctx.fillText(`快来扫码一起参加`, 260, 535)
      ctx.fillText(`打卡活动吧！`, 270, 550)
      // 设置标题 share_text
      const title = obj.share_text
      console.log(ctx.measureText(title).width)
      let rangeTxtArr = []
      let px = 0
      ctx.font = 'normal normal 14px sans-serif';
      ctx.setFillStyle('#fff')
      for (let i = 0; i < title.length; i++) {
        px += ctx.measureText(title[i]).width
        if (px > 300) {
          rangeTxtArr[0] = title.substr(0, i)
          rangeTxtArr[1] = title.substr(i)
          break
        } else {
          rangeTxtArr[0] = title.substr(0, i + 1)
        }
      }
      ctx.fillText(rangeTxtArr[0], 20, 600)
      if (px > 300) {
        ctx.fillText(rangeTxtArr[1], 20, 620)
      }
      ctx.draw()
      setTimeout(() => {
        wx.canvasToTempFilePath({
          // 通过id 指定是哪个canvas
          canvasId: "myCanvas",
          fileType: "png",
          success(res) {
            console.log(res.tempFilePath)
            // that.setData({
            //   tempFilePath: res.tempFilePath
            // })
            if (res.tempFilePath) {
              wx.hideLoading()
              that.setData({
                alert: true,
                tempFilePath: res.tempFilePath
              })
            }
            // resolve(res.tempFilePath)
          }
        })
      }, 500)
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    const { obj } = this.data
    return {
      title: obj.title,
      path: 'pages/clockDetail/index?shareId=' + obj.id,
      imageUrl: obj.image[0]
    }
  },
  onShareTimeline() {
    const { obj } = this.data
    return {
      title: obj.title,
      path: 'pages/clockDetail/index?shareId=' + obj.id,
      imageUrl: obj.image[0]
    }
  }
})